package cn.cdu.medical.util;

import cn.cdu.medical.entity.MedicalRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class AIResponseParser {
    
    /**
     * 解析AI回复内容，提取各个部分
     * @param response AI回复的文本内容
     * @return 包含各部分内容的Map
     */
    public Map<String, String> parseResponse(String response) {
        Map<String, String> sections = new HashMap<>();
        
        // 定义需要提取的部分
        String[] sectionTitles = {
            "主诉", "现病史", "初步诊断", "建议科室", "治疗建议"
        };
        
        // 使用正则表达式提取内容
        for (String title : sectionTitles) {
            Pattern pattern = Pattern.compile("【" + title + "】[\\s\\n]*([^【]+)", Pattern.DOTALL);
            Matcher matcher = pattern.matcher(response);
            
            if (matcher.find()) {
                String content = matcher.group(1).trim();
                // 移除内容中的Markdown标记
                content = content.replaceAll("\\*\\*|\\*", "");
                
                // 如果是科室名称，限制长度
                if ("建议科室".equals(title)) {
                    // 只取第一个科室，并限制长度
                    String[] depts = content.split("\\n");
                    if (depts.length > 0) {
                        content = depts[0].trim();
                        // 移除括号内的内容
                        content = content.replaceAll("\\([^)]*\\)", "").trim();
                        // 限制长度
                        if (content.length() > 50) {
                            content = content.substring(0, 50);
                        }
                    }
                }
                
                sections.put(title, content);
                log.debug("Extracted {} content: {}", title, content);
            } else {
                log.warn("Section {} not found in response", title);
                sections.put(title, "");
            }
        }
        
        return sections;
    }
    
    /**
     * 将解析后的内容转换为病历记录
     * @param sections 解析后的各部分内容
     * @return 病历记录对象
     */
    public MedicalRecord convertToMedicalRecord(Map<String, String> sections) {
        MedicalRecord record = new MedicalRecord();
        
        record.setChiefComplaint(sections.get("主诉"));
        record.setPresentIllness(sections.get("现病史"));
        record.setInitialDiagnosis(sections.get("初步诊断"));
        record.setDeptName(sections.get("建议科室"));
        record.setTreatmentPlan(sections.get("治疗建议"));
        
        // 设置其他默认值
        record.setVisitType("初诊");
        record.setStatus("INITIAL");
        
        return record;
    }
    
    /**
     * 直接从AI回复创建病历记录
     * @param response AI回复的文本内容
     * @return 病历记录对象
     */
    public MedicalRecord createMedicalRecord(String response) {
        Map<String, String> sections = parseResponse(response);
        return convertToMedicalRecord(sections);
    }
} 
 
 
 